import utils from "../utils"

function findCommandTargets(model, pattern, type) {
  const targets = []
  const layers = utils.pluck(model.getLayers(), 'layer')
  let matches = findMatchingLayers(layers, pattern)
  if (type) {
    matches = matches.filter((lyr) => {
      return lyr.geometry_type === type
    })
  }
  model.getDatasets().forEach((dataset) => {
    const layers = dataset.layers.filter((lyr) => {
      return matches.indexOf(lyr) > -1
    })
    if (layers.length > 0) {
      targets.push({
        layers: layers,
        dataset: dataset
      })
    }
  })
  return targets
}
function findMatchingLayers(layers, pattern) {
  const matches = []
  const index = {}
  pattern.split(',').forEach((subpattern) => {
    const test = getLayerMatch(subpattern)
    layers.forEach((lyr, layerId) => {
      if (layerId in index) return
      if (test(lyr, layerId + 1)) {
        lyr.target_id = matches.length
        matches.push(lyr)
        index[layerId] = true
      } else {
        lyr.target_id = -1
      }
    })
  })
  return matches
}
function getLayerMatch(pattern) {
  const isIndex = utils.isInteger(Number(pattern))
  const nameRxp = isIndex ? null : utils.wildcardToRegExp(pattern)
  return (lyr, i) => {
    return isIndex ? String(i) === pattern : nameRxp.test(lyr.name || '')
  }
}
export default {
  findCommandTargets,
}